package com.api.demo.controller;

import com.api.demo.entity.User;
import com.api.demo.mapper.UserFollowMapper;
import com.api.demo.mapper.UserMapper;
import com.api.demo.service.UserService;
import lombok.Data;

import javax.websocket.server.PathParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.api.demo.util.JwtUtil;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserFollowMapper userFollowMapper;

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody RegisterRequest request) {
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword());
        user.setEmail(request.getEmail());

        userService.register(user);
        return ResponseEntity.ok(new MessageResponse("注册成功"));
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
        String token = userService.login(request.getUsername(), request.getPassword());
        return ResponseEntity.ok(new LoginResponse(token));
    }

    @GetMapping("/user")
    public ResponseEntity<?> getUserInfo(@RequestHeader("Authorization") String token) {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        User user = userService.findByUsername(username);

        if (user == null) {
            return ResponseEntity.badRequest().body(new MessageResponse("用户不存在"));
        }

        UserInfoResponse userInfo = new UserInfoResponse();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setEmail(user.getEmail());
        userInfo.setAvatar(user.getAvatar());

        return ResponseEntity.ok(userInfo);
    }

    @PutMapping("/user/avatar")
    public ResponseEntity<?> updateAvatar(@RequestHeader("Authorization") String token,
            @RequestBody UpdateAvatarRequest request) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        if (!jwtUtil.validateToken(token)) {
            return ResponseEntity.badRequest().body(new MessageResponse("无效的token"));
        }

        String username = jwtUtil.getUsernameFromToken(token);
        User user = userService.findByUsername(username);

        if (user == null) {
            return ResponseEntity.badRequest().body(new MessageResponse("用户不存在"));
        }

        boolean updated = userService.updateAvatar(user.getId(), request.getAvatarUrl());
        if (updated) {
            return ResponseEntity.ok(new MessageResponse("头像更新成功"));
        } else {
            return ResponseEntity.badRequest().body(new MessageResponse("头像更新失败"));
        }
    }

    @GetMapping("/message/{id}")
    public ResponseEntity<?> getMessage(@PathVariable Long id) {
        // 获取当前认证用户
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        User currentUser = userService.findByUsername(username);

        // 获取目标用户
        User targetUser = userMapper.selectById(id);

        // 创建返回对象
        Message message = new Message();
        message.setId(targetUser.getId());
        message.setAvatar(targetUser.getAvatar());
        message.setUsername(targetUser.getUsername());

        // 正确查询关注状态（当前用户是否关注了目标用户）
        boolean isFollowing = userFollowMapper.findFollowRelationship(
                currentUser.getId(), // followerId (关注者)
                id // followingId (被关注者)
        ) != null;

        message.setFollow(isFollowing);

        return ResponseEntity.ok(message);
    }

    @Data
    public static class RegisterRequest {
        private String username;
        private String password;
        private String email;
    }

    @Data
    public static class LoginRequest {
        private String username;
        private String password;
    }

    @Data
    public static class LoginResponse {
        private String token;

        public LoginResponse(String token) {
            this.token = token;
        }
    }

    @Data
    public static class MessageResponse {
        private String message;

        public MessageResponse(String message) {
            this.message = message;
        }
    }

    @Data
    public static class UserInfoResponse {
        private Long id;
        private String username;
        private String email;
        private String avatar;
    }

    @Data
    public static class UpdateAvatarRequest {
        private String avatarUrl;
    }

    @Data
    public static class Message {
        private String username;
        private Long id;
        private String avatar;
        private boolean isFollow;
    }
}